<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
            v-model="queryParams.supplierName"
            placeholder="请输入供应商名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="供应商状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择供应商状态" clearable>
          <el-option
              v-for="dict in sys_status_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--搜索----------------------------------------------------------------------------------->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:suppliers:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:suppliers:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:suppliers:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:suppliers:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--表格------------------------------------------------------------------------------------------->

    <el-table v-loading="loading" :data="suppliersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="供应商编号" align="center" prop="supplierId"/>
      <el-table-column label="供应商名称" align="center" prop="supplierName"/>
      <el-table-column label="联系人姓名" align="center" prop="contactName"/>
      <el-table-column label="联系电话" align="center" prop="contactPhone"/>
      <el-table-column label="创建时间" align="center" prop="creationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creatorName"/>
      <el-table-column label="供应商状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_status_type" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column width="240" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:suppliers:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:suppliers:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改供应商信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="suppliersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="供应商名称" label-width="120px" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商名称"/>
        </el-form-item>
        <el-form-item label="联系人姓名" label-width="120px" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名"/>
        </el-form-item>
        <el-form-item label="联系电话" label-width="120px" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="供应商状态" label-width="120px" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in sys_status_type"
                :key="dict.value"
                :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Suppliers">
import {listSuppliers, getSuppliers, delSuppliers, addSuppliers, updateSuppliers} from "@/api/system/suppliers";
import {formatDateTime} from "@/api/system/clinics";

const {proxy} = getCurrentInstance();
const {sys_status_type} = proxy.useDict('sys_status_type');

const suppliersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierName: null,
    contactName: null,
    contactPhone: null,
    creationTime: null,
    creatorId: null,
    status: null
  },
  rules: {
    supplierName: [
      {required: true, message: "供应商名称不能为空", trigger: "blur"}
    ],
    contactName: [
      {required: true, message: "联系人姓名不能为空", trigger: "blur"}
    ],
    contactPhone: [
      {required: true, message: "联系电话不能为空", trigger: "blur"}
    ],
    creationTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
    creatorId: [
      {required: true, message: "员工ID不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "供应商状态不能为空", trigger: "change"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询供应商信息列表 */
function getList() {
  loading.value = true;
  listSuppliers(queryParams.value).then(response => {
    suppliersList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    supplierId: null,
    supplierName: null,
    contactName: null,
    contactPhone: null,
    creationTime: null,
    creatorId: null,
    status: null
  };
  proxy.resetForm("suppliersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.supplierId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加供应商信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _supplierId = row.supplierId || ids.value
  getSuppliers(_supplierId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改供应商信息";
  });
}

/**
 * 提交表单函数
 * 该函数用于处理表单提交逻辑，包括验证表单、更新或添加供应商信息，并显示相应的消息提示。
 */
function submitForm() {
  // 通过当前用户id添加，创建时间为当前时间
  // 从localStorage中获取userId，并设置到表单的creatorId属性
  form.value.creatorId = localStorage.getItem("userId");
  // 格式化当前日期时间为字符串，并设置到表单的creationTime属性
  form.value.creationTime = formatDateTime(new Date());
  console.log(form.value);
  // 验证表单的有效性
  proxy.$refs["suppliersRef"].validate(valid => {
    // 如果表单验证通过
    if (valid) {
      // 判断供应商id是否存在
      if (form.value.supplierId != null) {
        // 如果存在，调用updateSuppliers函数更新供应商信息
        updateSuppliers(form.value).then(response => {
          // 显示修改成功的提示消息
          proxy.$modal.msgSuccess("修改成功");
          // 关闭当前的模态框
          open.value = false;
          // 重新获取供应商列表
          getList();
        });
      } else {
        // 如果不存在，调用addSuppliers函数添加新的供应商信息
        addSuppliers(form.value).then(response => {
          // 显示新增成功的提示消息
          proxy.$modal.msgSuccess("新增成功");
          // 关闭当前的模态框
          open.value = false;
          // 重新获取供应商列表
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _supplierIds = row.supplierId || ids.value;
  proxy.$modal.confirm('是否确认删除供应商信息编号为"' + _supplierIds + '"的数据项？').then(function () {
    return delSuppliers(_supplierIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/suppliers/export', {
    ...queryParams.value
  }, `suppliers_${new Date().getTime()}.xlsx`)
}

getList();
</script>
